Dart List operator []=
Syntax & Examples
Syntax of List.operator []=
The syntax of List.operator []= operator is:
operator []=(int index, E value) → voidThis operator []= operator of List sets the value at the given index in the list to value.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
index | required | the index at which to set the value in the list |
value | required | the value to set at the specified index |
✐ Examples
1 Set element at index 2 to 10 in a list of numbers
In this example,
- We create a list
numberscontaining integers. - We use the
[]=operator to set the element at index 2 to the value 10. - We print the modified
numberslist to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
numbers[2] = 10;
print(numbers);
}Output
[1, 2, 10, 4, 5]
2 Set element at index 1 to 'd' in a list of characters
In this example,
- We create a list
characterscontaining characters. - We use the
[]=operator to set the element at index 1 to the character 'd'. - We print the modified
characterslist to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c'];
characters[1] = 'd';
print(characters);
}Output
[a, d, c]
3 Set element at index 0 to 'Eve' in a list of names
In this example,
- We create a list
namescontaining strings. - We use the
[]=operator to set the element at index 0 to the string 'Eve'. - We print the modified
nameslist to standard output.
Dart Program
void main() {
List<String> names = ['Alice', 'Bob', 'Charlie'];
names[0] = 'Eve';
print(names);
}Output
[Eve, Bob, Charlie]
Summary
In this Dart tutorial, we learned about operator []= operator of List: the syntax and few working examples with output and detailed explanation for each example.